package com.tanvir.sdl.client;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import java.net.URLConnection;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.htmlparser.Parser;


public class DLThread implements Runnable {
    private static Logger logger = Logger.getLogger(DLThread.class.getPackage().getName());
    private String url;
    private String name;
    private File dir;

    public DLThread(String url, String name, File dir) {
        super();
        this.url = url;
        this.name = name;
        this.dir = dir;
    }

    public void run() {
        boolean restart = false;
        do {
            restart = false;
            try {
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File f = new File(dir, name);
                Parser p = new Parser(url);
                URLConnection connection = p.getConnection();

                BufferedInputStream bis = new BufferedInputStream(connection.getURL().openStream());
                logger.log(Level.INFO, "Downloading : {0}", f.getAbsolutePath());
                FileOutputStream fos = new FileOutputStream(f);
                byte[] b = new byte[4096];
                try {
                    //int b = bis.read();
                    int len;
                    while ((len = bis.read(b)) > 0) {
                        fos.write(b, 0, len);
                    }
                } catch (IOException ioe) {
                    restart = true;
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                    if (bis != null) {
                        bis.close();
                    }
                }
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Error : ", e);
            }
        } while (restart);
    }
}
